package com.net.xpay.web.controller.merchant;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.net.common.annotation.WriteTransactional;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.common.model.ResultPagedList;
import com.net.common.util.SerializationUtil;
import com.net.xpay.common.domain.User;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.domain.TaokeDetectionBatch;
import com.net.xpay.core.domain.TaokeDetectionRecord;
import com.net.xpay.core.enums.TaokeDetectionBatchStatus;
import com.net.xpay.core.enums.TaokeStatus;
import com.net.xpay.core.manager.TaokeDetectionBatchManager;
import com.net.xpay.core.manager.TaokeDetectionRecordManager;
import com.net.xpay.core.model.ResultModel;
import com.net.xpay.core.model.TaokeDetectionBatchSearchModel;
import com.net.xpay.core.service.TaokeDetectionService;
import com.net.xpay.core.utils.ExcelImportUtil;
import com.net.xpay.web.secutiry.RequestUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 2020/5/7 13:31

 */
@RestController
@Slf4j
@RequestMapping("/merchant/taoke-detection-batch")
@Api(tags = "商户/批量查淘客订单", description = "商户 批量查淘客订单 net")
public class TaokeDetectionBatchController {

    @Autowired
    private TaokeDetectionBatchManager taokeDetectionBatchManager;

    @Autowired
    private TaokeDetectionRecordManager taokeDetectionRecordManager;

    @Autowired
    private TaokeDetectionService taokeDetectionService;

    /**
     * 确认查询
     */
    @ApiOperation("确认查询")
    @PostMapping("/confirm")
    public ResultData<TaokeDetectionBatch> confirmTaokeDetectionBatch(@ApiIgnore @RequestUser User merchant, HttpServletResponse response, Long id) {

        return new ResultData<>(taokeDetectionService.batchDetection(merchant, id));
    }

    /**
     * 搜索
     */
    @ApiOperation("搜索")
    @PostMapping("/search")
    public ResultPagedList<TaokeDetectionBatch> search(@ApiIgnore @RequestUser User merchant, @RequestBody TaokeDetectionBatchSearchModel searchModel) {
        Preconditions.checkArgument(searchModel != null);
        searchModel.setUserId(merchant.getId());
        List<TaokeDetectionBatch> records = taokeDetectionBatchManager.search(searchModel);
        long count = taokeDetectionBatchManager.searchCount(searchModel);

        return new ResultPagedList<>(records, count, searchModel);
    }


    /**
     * 批量查淘客订单 excel导入
     */
    @ApiOperation("批量查淘客订单 excel导入")
    @PostMapping("/import")
    @WriteTransactional
    public ResultData<TaokeDetectionBatch> importTaokeDetectionBatch(@RequestParam(value = "file", required = false) MultipartFile file, @ApiIgnore @RequestUser User merchant) {
        Preconditions.checkArgument(file != null);
        String fileName = file.getOriginalFilename();
        Preconditions.checkArgument(!Strings.isNullOrEmpty(fileName));
        if (!(fileName.endsWith("xls") || fileName.endsWith("xlsx"))) {
            log.warn("importTaokeDetectionBatch file suffix error：" + fileName);
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "上传的文件格式错误|" + fileName);
        }
        long size = file.getSize();

        if (size > 10 * 1024 * 1024L) {
            log.warn("iimportTaokeDetectionBatch|file is too large|fileSize={}|userId={}", size, merchant.getId());
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "上传文件最大10M");
        }

        try {
            Workbook workBook = ExcelImportUtil.getWorkbook(file.getOriginalFilename(), file.getInputStream());
            Sheet sheet = workBook.getSheetAt(0);
            ResultModel<List<String>> resultModel = ExcelImportUtil.importListFromExcelUtilNull(workBook, sheet, 2, null);
            log.info("importTaokeDetectionBatch resultModel={}", SerializationUtil.obj2String(resultModel));
            if (!resultModel.isSuccess()) {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, resultModel.getResultMessage());
            }

            List<TaokeDetectionRecord> records = checkImportTaokeDetectionBatchData(resultModel.getData(), merchant);

            //保存导入记录
            return new ResultData<>(saveBatchRecords(merchant, records, file));
        } catch (IOException e) {
            log.info("importPayTrans error", e);
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "系统错误 请联系客服");
        }
    }

    private TaokeDetectionBatch saveBatchRecords(User merchant,  List<TaokeDetectionRecord> records, MultipartFile file) throws IOException {
        TaokeDetectionBatch instance = TaokeDetectionBatch.getInstance();
        instance.setUserId(merchant.getId());
        instance.setStatus(TaokeDetectionBatchStatus.WAIT);
        instance.setTotalCount(records.size());
        instance.setOutBatchNo(null);
        instance.setTaokeUnitPrice(merchant.getTaokeUnitPrice());
        instance.setTaokePrice(instance.getTotalCount() * merchant.getTaokeUnitPrice());

        taokeDetectionBatchManager.save(instance);

        for (TaokeDetectionRecord record : records) {
            record.setBatchNo(instance.getBatchNo());
            record.setBatchId(instance.getId());
        }

        taokeDetectionRecordManager.batchSave(records);

        return instance;
    }

    private List<TaokeDetectionRecord> checkImportTaokeDetectionBatchData(List<List<String>> datas, User merchant) {
        List<TaokeDetectionRecord> records = Lists.newArrayList();
        StringBuilder errMessage = new StringBuilder();
        for (int i = 0; i < datas.size(); i++) {
            List<String> row = datas.get(i);
            //淘宝订单号
            String tid = row.get(0);
            //买家手机号
            String buyerMobile = row.get(1);
            //买家旺旺号
            String ww = row.get(2);

            if (Strings.isNullOrEmpty(tid)) {
                errMessage.append(" (第").append(i + 3).append("行:").append("淘宝订单号必填");
                continue;
            }

            if (Strings.isNullOrEmpty(buyerMobile)) {
                errMessage.append(" (第").append(i + 3).append("行:").append("买家手机号必填");
                continue;
            }

            if (Strings.isNullOrEmpty(ww)) {
                errMessage.append(" (第").append(i + 3).append("行:").append("买家旺旺号必填");
                continue;
            }

            TaokeDetectionRecord taokeDetectionRecord = TaokeDetectionRecord.getInstance();
            taokeDetectionRecord.setUserId(merchant.getId());
            taokeDetectionRecord.setTid(tid);
            taokeDetectionRecord.setBuyerMobile(buyerMobile);
            taokeDetectionRecord.setWw(ww);
            taokeDetectionRecord.setStatus(TaokeStatus.WAIT);
            records.add(taokeDetectionRecord);
        }

        if (!Strings.isNullOrEmpty(errMessage.toString())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, errMessage.toString());
        }

        if (CollectionUtils.isEmpty(records)) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "至少上传一条打款记录");
        }

        if (records.size() > 10000) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "一次最多查询1w笔");
        }

        return records;
    }
}
